<?php

namespace app\middleware;

use app\admin\app\model\Card;
use support\Db;
use support\Redis;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class Auth implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $no = ['app\api\controller\ClippingController', 'app\api\controller\CapcutController'];
        $token = $request->header('token');
        if (!in_array($request->controller, $no) && $request->action !== 'login') {
            if (empty($token)) {
                return json(['code' => 0, 'msg' => 'token不存在']);
            }
            $card_id = Redis::get($token);
            $row = Card::where('status', 1)->find($card_id);
            if (empty($row)) {
                return json(['code' => 0, 'msg' => 'token错误']);
            }
            if (strtotime($row->end_time) < time()) {
                return json(['code' => 0, 'msg' => '卡密已过期']);
            }
            $request->card = $row;
        }
        return $handler($request);
    }

}
